package com.training.java.redbox.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.training.java.redbox.domain.Customer;
import com.training.java.redbox.domain.CustomerDAO;
import com.training.java.redbox.domain.CustomerDaoJdbcImpl;
import com.training.java.redbox.domain.DAOException;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		CustomerDAO dao = new CustomerDaoJdbcImpl();
		Customer  customer = null;
		
		RequestDispatcher rd = null;
		
		try {
				customer = dao.lonin(username, password);
			
			
			if (customer == null)
			{
				request.setAttribute("username", username);
				request.setAttribute("ErrorMessage", "Please enter the correct username and password");
				rd = request.getRequestDispatcher("/Login.jsp");
				
			}
			else{
				HttpSession  session = request.getSession();
				session.setAttribute("Customer", customer);
				rd = request.getRequestDispatcher("/");
			
			}
			rd.forward(request, response);	
		} catch (DAOException e) {
			e.printStackTrace();
		}
		
	}

}
